import { reqGetShopCartInfo, reqDeleteCartById, reqUpdateCheckedById } from '@/api/index.js'

const state = {
  cartList: {}
}
const mutations = {
  GETSHOPCARTINFO(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  async getShopCartInfo({ commit }) {
    let result = await reqGetShopCartInfo();
    if (result.code === 200) {
      commit("GETSHOPCARTINFO", result.data)
    }
  },
  async deleteCartById({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId);
    if (result.code === 200) {
      console.log('ok');
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  deleteAllCheckCart({ dispatch, getters }) {
    let PromiseAll = [];
    getters.cartList.cartInfoList.forEach(item => {
      if (item.isChecked == 1) {
        let promise = dispatch('deleteCartById', item.skuId)
        PromiseAll.push(promise);
      }
    });
    return Promise.all(PromiseAll)
  },
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked);
    if (result.code === 200) {
      console.log('ok');
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  updateAllCartChecked({ dispatch, state }, isChecked) {
    let PromiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch('updateCheckedById', { skuId: item.skuId, isChecked: isChecked })
      PromiseAll.push(promise)
    });
    return Promise.all(PromiseAll)
  }

}

const getters = {
  cartList(state) {
    return state.cartList[0] || {};
  }
}

export default {
  state,
  mutations,
  actions,
  getters

}